using System;
using Microsoft.SPOT;

namespace nRF24L10P.Roles
{
    public class SimpleReceiverRole:IRole
    {
        private nRF24L10P device;
        private object syncRoot = new object();
        public byte[] Address { get; set; }
        //private int length;
        DataReadPipe reader;

        public bool IsRunning { get; set; }
        //public int BufferSize { get; private set; }
        public delegate void DataArrivedDelegate(byte[] buffer);
        public event DataArrivedDelegate DataArrived;

        public void Start()
        {
            if (IsRunning)
            {
                return;
            }
            device.Status = DeviceStatusEnum.PowerDown; //shut down device for config

            reader = device.RXPipes[1]; //use the 2nd receive channel, 1st channel is reserved for ACK in TX mode

            //enable autoACK
            reader.AutoACKEnabled = true;

            //enable dynamic package length by default
            device.Config.DynamicPayloadLengthEnabled = true;

            reader.AutoACKEnabled = true;
            reader.DynamicPayloadLengthEnabled = true;
            reader.Address = this.Address;
            reader.Enabled = true;
            device.FlushRX();
            device.FlushTX();

            device.OnInterrupt += device_OnInterrupt;

            device.Status = DeviceStatusEnum.StandBy;

            device.Status = DeviceStatusEnum.RXMode;// start listening
            IsRunning = true;
        }

        private void device_OnInterrupt(Register.Register_STATUS status)
        {
            if (status.RX_DR && DataArrived!=null)// data arrived
            {
                DataArrived(reader.ReadBufferAll());

                device.Status = DeviceStatusEnum.StandBy;//put the device to idle status for status saving

                //clear the flag, by wring back bit flag 1 to source, we can clear the flag in register
                status.Save();

                device.Status = DeviceStatusEnum.RXMode;
            }
            
        }

        public void Stop()
        {
            if (!IsRunning)
            {
                return;
            }
           
            device.OnInterrupt -= device_OnInterrupt;
            device.Status = DeviceStatusEnum.StandBy;            
            device.Status = DeviceStatusEnum.PowerDown;
            IsRunning = false;
        }

        public void AttachDevice(nRF24L10P device)
        {
            this.device = device;
        }

        public void DetachDevice()
        {
            this.device = null;
        }
    }
}
